<template>
	<view>
		<view class="content" @tap="uploadAndCompression()">
			<template v-if="positiveFlag">
				<image style="width: 200rpx; height: 200rpx;" src="/static/logo.png"> </image>
				<view class="font26"> 点击拍摄上传图片 </view>
			</template>
			<image v-else style="width: 200rpx; height: 200rpx;border-radius: 10rpx;"  :src="positiveSrc"></image>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				positiveFlag:true,
				positiveSrc:'',
				compressionRatio:3  //  压缩系数 压缩为原来的1/3
			}
		},
		onLoad(){
		
		},
		methods: {
			async uploadAndCompression(){
				let _this = this;
				uni.chooseImage({
					sizeType: ['compressed'], //  original 原图，compressed 压缩图，默认二者都有  (h5没有效果)
					sourceType: ['album','camera'],  //  album 从相册选图，camera 使用相机
				    success: function (res) {
						console.log(res.tempFiles[0])
						console.log("压缩前图片大小:",_this.getFileSize(res.tempFiles[0].size))
						let path = res.tempFilePaths[0]
						// 图片回显
						_this.positiveFlag = false
						_this.positiveSrc = path
						
						//--压缩图片--start--
						uni.getImageInfo({
							src: path,
							success: function (res) {
								let canvasWidth = res.width / _this.compressionRatio; //  图片原始长宽  压缩为原来的1/3
								let canvasHeight = res.height / _this.compressionRatio;
								let img = new Image()
								img.src = path
								img.onload = function(){
									var quality = 1;  // 图片质量
									let canvas = document.createElement('canvas');
									let ctx = canvas.getContext('2d')
									canvas.width = canvasWidth 
									canvas.height = canvasHeight 
									ctx.drawImage(img, 0, 0, canvasWidth, canvasHeight)
									canvas.toBlob(function(fileSrc) {
										let files = new File([fileSrc],"压缩后")
										console.log(files)
										console.log("压缩后图片大小:",_this.getFileSize(files.size))
										
										//压缩完  上传图片操作
										let imgSrc = window.URL.createObjectURL(fileSrc)
										_this.downloadFile(imgSrc)
									})
								}
							}
						})
						//--压缩图片--end--
				    }
				});
			},
			downloadFile(imgSrc){  //上传文件
				let _this = this
				var uper = uni.uploadFile({
					// 需要上传的地址  http://自己的域名/uploadIdImgs
					url:'http://自己的域名/uploadIdImgs',
					// filePath  需要上传的文件
					filePath: imgSrc,
					name: 'idCardImg',
					success(res1) {
						// 显示上传信息
						console.log(JSON.stringify(res1))
						//处理业务
						
					 },
					 fail(res1){
						alert("上传失败,请重新上传--"+JSON.stringify(res1))
					 }
				});
			},
			dataURLtoBlob(dataurl) {
				var arr = dataurl.split(',');
				var mime = arr[0].match(/:(.*?);/)[1];
				var bstr =atob(arr[1]);    
				var n = bstr.length;     
				var u8arr =new Uint8Array(n); 
				while (n--) {
					u8arr[n] = bstr.charCodeAt(n);
				}
				return new Blob([u8arr], {type: mime });
			},
			getFileSize(fileSize){
			    var size = (fileSize/1024).toFixed(2) + "KB"
				var sizeMb = (fileSize/(1024 * 1024)).toFixed(2) + "MB"
			
			    var sizeStr = size + "";                        //转成字符串
			    var index = sizeStr.indexOf(".");                    //获取小数点处的索引
			    var dou = sizeStr.substr(index + 1 ,2)            //获取小数点后两位的值
			    if(dou == "00"){                                //判断后两位是否为00，如果是则删除00
			        return sizeStr.substring(0, index) + sizeStr.substr(index + 3, 2)
			    }
			    return size+" -- "+sizeMb;
			}
		}
	}
</script>

<style>
.content {
		display: -webkit-flex;
		display: flex;
		-webkit-flex-direction: column;
		flex-direction: column;
		-webkit-justify-content: center;
		justify-content: center;
		-webkit-align-items: center;
		align-items: center;
		
		padding-top: 60rpx;
	}
</style>
